package com.kb.design.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.kb.design.constant.Constants;
import com.kb.design.dto.CustomUserDTO;
import com.kb.design.dto.ProjectReview;
import com.kb.design.dto.TaskSplittingDTO;
import com.kb.design.entity.*;
import com.kb.design.enums.DesignStatus;
import com.kb.design.mapper.postgreSQL.*;
import com.kb.design.service.CustomUserService;
import com.kb.design.service.DailyService;
import com.kb.design.service.DeptService;
import com.kb.design.service.DesignRoleService;
import com.kb.design.vo.DesignDeptVO;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * (CustomUser)表服务实现类
 *
 * @author makejava
 * @since 2023-08-22 10:57:17
 */
@Service
@DS("slave-1")
public class DailyServiceImpl extends ServiceImpl<DailyMapper, DesignDaily> implements DailyService {

    @Resource
    private DailyMapper dailyMapper;
    @Resource
    private CustomUserService userService;
    @Resource
    private CustomUserMapper userMapper;
    @Resource
    private DesignResponsiblePersonMapper responsiblePersonMapper;
    @Resource
    private DesignRoleService designRoleService;
    @Resource
    private DeptService deptService;
    @Resource
    private ProjectMapper projectMapper;
    @Resource
    private DesignDeptMapper designDeptMapper;

    @Override
    public void dailyAdd(DesignDaily daily) {
        String nickName = userService.queryNickName(daily.getCreateBy());
        daily.setCreateByName(nickName);
        daily.setDaily(LocalDate.now());
        //先删除 只留一份当天最新的
        LambdaQueryWrapper<DesignDaily> delWrapper = Wrappers.lambdaQuery();
        delWrapper.eq(DesignDaily::getDaily, new Date()).eq(DesignDaily::getCreateBy, daily.getCreateBy());
        dailyMapper.delete(delWrapper);
        dailyMapper.insert(daily);
    }

    @Override
    public List<DesignDaily> queryLatestList(DesignDaily daily) {
        /**
         * 不做权限  根据部门id 查询部门下有什么人 然后查这些人的日报
         */
        Long deptId = daily.getDeptId();
        List<CustomUser> userList = this.queryUserBydeptId(deptId);
        if (CollectionUtils.isEmpty(userList)) {
            return fetchCurrentUserDailies(daily);
        }

        Set<String> userIds = userList.stream()
                .map(CustomUser::getCode)
                .collect(Collectors.toSet());

        // 查询所有用户当日日报
        List<DesignDaily> designDailies = dailyMapper.selectList(
                Wrappers.lambdaQuery(DesignDaily.class)
                        .in(DesignDaily::getCreateBy, userIds)
                        .eq(DesignDaily::getDaily, daily.getDaily())
        );

        // 构建 map：key=userId，value=daily
        Map<String, DesignDaily> dailyMap = designDailies.stream()
                .collect(Collectors.toMap(DesignDaily::getCreateBy, d -> d));

        // 填充结果（有记录就返回记录，没有则构造基础信息）
        List<DesignDaily> resultList = new ArrayList<>();
        for (CustomUser user : userList) {
            DesignDaily result = dailyMap.getOrDefault(user.getCode(), new DesignDaily());
            if (result.getId() == null) {
                result.setCreateBy(user.getCode());
                result.setCreateByName(user.getName());
            }
            resultList.add(result);
        }

        // 将当前用户的数据排在最前面
//        List<DesignDaily> designDailies1 = sortResultByCurrentUserFirst(resultList, currentUserId);
//        if (CollectionUtil.isNotEmpty(designDailies1)) {
//            DesignDaily promptInfo = this.getPromptInfo(designDailies1.get(0));
//            promptInfo.setCreateBy(designDailies1.get(0).getCreateBy());
//            designDailies1.set(0, promptInfo);
//        }
        return resultList;
    }

    @Override
    public List<DesignDaily> queryTodyFreeList(DesignDaily daily) {
        ArrayList<Integer> numbers = new ArrayList<>();
        if (daily.getFreeSelect() == null){
            numbers = Lists.newArrayList(2,3, 4);
        }else {
            numbers.add(daily.getFreeSelect());
        }
        List<DesignDaily> designDailies = dailyMapper.queryTodyFreeList(daily.getCreateByName(), numbers, daily.getFreeTime());
        //查询设计部门未写日报的人员 标记了设计部门属性的为设计部门
        LambdaQueryWrapper<DesignDept> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DesignDept::getDelFlag,"0").eq(DesignDept::getDeptFunctions,"2");
        List<DesignDept> designDepts = designDeptMapper.selectList(queryWrapper);
        if (CollectionUtil.isNotEmpty(designDepts)){
            List<Long> list = designDepts.stream().map(DesignDept::getDeptId).toList();
            LambdaQueryWrapper<CustomUser> userQuery = Wrappers.lambdaQuery();
            userQuery.in(CustomUser::getDeptId, list);
            userQuery.eq(StringUtils.isNotBlank(daily.getCreateByName()),CustomUser::getName, daily.getCreateByName());
            List<CustomUser> userList = userMapper.selectList(userQuery);
            List<String> stringList = designDailies.stream().map(DesignDaily::getCreateBy).toList();
            if (CollectionUtil.isNotEmpty(userList)){
                //数据封装
                for (CustomUser user : userList) {
                    //过滤designDailies已存在的人
                    if (CollectionUtil.isNotEmpty(stringList) && stringList.contains(user.getCode()) || (Objects.nonNull(daily.getFreeSelect()) && daily.getFreeSelect() != 0)) {
                        continue;
                    }
                    DesignDaily designDaily = new DesignDaily();
                    designDaily.setCreateByName(user.getName());
                    designDaily.setDeptName(user.getDeptName());
                    designDaily.setDaily(LocalDate.now());
                    designDaily.setFreeSelect(0);
                    designDailies.add(designDaily);
                }
            }
        }
        return designDailies;
    }

    // 查询当前用户自己的日报
    private List<DesignDaily> fetchCurrentUserDailies(DesignDaily daily) {
        List<DesignDaily> designDailies = dailyMapper.selectList(
                Wrappers.lambdaQuery(DesignDaily.class)
                        .eq(DesignDaily::getCreateBy, daily.getCreateBy())
                        .eq(DesignDaily::getDaily, daily.getDaily())
        );
        if (CollectionUtils.isEmpty(designDailies)){
            DesignDaily designDaily = new DesignDaily();
            designDaily.setCreateBy(daily.getCreateBy());
            designDaily.setCreateByName(userService.queryNickName(daily.getCreateBy()));
            designDailies.add(designDaily);
        }
        DesignDaily promptInfo = this.getPromptInfo(designDailies.get(0));
        promptInfo.setCreateBy(designDailies.get(0).getCreateBy());
        designDailies.set(0, promptInfo);
        return designDailies;
    }

    // 排序方法：将当前用户数据放在首位
    private List<DesignDaily> sortResultByCurrentUserFirst(List<DesignDaily> list, String currentUserId) {
        return list.stream()
                .sorted((o1, o2) -> {
                    if (currentUserId.equals(o1.getCreateBy())) return -1;
                    if (currentUserId.equals(o2.getCreateBy())) return 1;
                    return 0;
                })
                .collect(Collectors.toList());
    }

    @Override
    public DesignDaily getPromptInfo(DesignDaily daily) {
        //先查询当前是否有数据
        LambdaQueryWrapper<DesignDaily> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DesignDaily::getCreateBy, daily.getCreateBy());
        queryWrapper.eq(DesignDaily::getDaily, new Date());
        List<DesignDaily> designDailies = dailyMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(designDailies)) {
            return designDailies.get(0);
        } else {
            //没有返回项目提示 今天的数据：参与项目的进度 昨日数据：昨天的今日数据
            DesignDaily designDaily = new DesignDaily();
            //查询昨天的数据
            LocalDate yesterday = LocalDate.now().minusDays(1);
            DesignDaily yesterdayData = dailyMapper.selectOne(
                    Wrappers.lambdaQuery(DesignDaily.class)
                            .eq(DesignDaily::getCreateBy, daily.getCreateBy())
                            .eq(DesignDaily::getDaily, yesterday)
            );
            if (yesterdayData != null) {
                designDaily.setYesterdayContent(yesterdayData.getTodayContent());
            }
            //查询项目信息
            List<DesignProject> projectList = projectMapper.queryProjectListByCode(Integer.valueOf(daily.getCreateBy()));
            if (!CollectionUtils.isEmpty(projectList)) {
                int num = 1;
                String todayStr = "";
                for (DesignProject designProject : projectList) {
                    String completionRate = designProject.getCompletionRate() != null
                            ? String.valueOf(designProject.getCompletionRate())+"%"
                            : "0%";
                    todayStr += num + "." + designProject.getProjectName() + " "
                            + DesignStatus.getName(designProject.getStatus()) + " "
                            + completionRate + "\n";  // 使用 \n 表示换行
                    num++;
                }
                designDaily.setTodayContent(todayStr);
            }
            return designDaily;
        }
    }

    @Override
    public Map<String, Object> getNoDailyCount(DesignDaily daily) {
        Long deptId = daily.getDeptId();
        List<CustomUser> userList = this.queryUserBydeptId(deptId);

        Map<String, Object> result = new HashMap<>();
        //当天提交日报的人
        List<DesignDaily> designDailies = dailyMapper.selectList(
                Wrappers.lambdaQuery(DesignDaily.class)
                        .eq(DesignDaily::getDaily, daily.getDaily())
        );
        if (!CollectionUtils.isEmpty(userList)) {
            // 提取 designDailies 中所有 createBy 用户 ID 集合
            Set<String> submittedUsers = designDailies.stream()
                    .map(DesignDaily::getCreateBy)
                    .collect(Collectors.toSet());

            // 过滤掉已提交日报的用户
            List<CustomUser> filteredUserList = userList.stream()
                    .filter(user -> !submittedUsers.contains(user.getCode()))
                    .toList();
        // 将 name 字段拼接成字符串，用中文逗号分隔
            String names = filteredUserList.stream()
                    .map(CustomUser::getName)
                    .filter(Objects::nonNull)
                    .collect(Collectors.joining("，"));

            result.put("names", names);
            result.put("count", filteredUserList.size());
        }
        return result;
    }

    @Override
    public void taskSplitting(TaskSplittingDTO taskSplittingDTO) {
        DesignResponsiblePerson designResponsiblePerson = new DesignResponsiblePerson();
        BeanUtils.copyProperties(taskSplittingDTO, designResponsiblePerson, "id");
        designResponsiblePerson.setDel(Constants.DEL_FLAG_NO);
        designResponsiblePerson.setCreateBy(taskSplittingDTO.getCreateBy());
        designResponsiblePerson.setCreateTime(LocalDateTime.now());
        responsiblePersonMapper.insert(designResponsiblePerson);
//        }
    }

    @Override
    public List<DesignDaily> selectDailyInfo(DesignDaily daily) {
        LambdaQueryWrapper<DesignDaily> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DesignDaily::getCreateBy, daily.getCreateBy());
        //按时间倒序
        queryWrapper.orderByDesc(DesignDaily::getCreateTime);
        return dailyMapper.selectList(queryWrapper);
    }

    /**
     * 根据传入工号 查询此人的数据权限 只查设计部门
     *
     * @param code
     * @return
     */
    public List<CustomUser> userDataRights(String code) {
        //判断当前用户是否是admin 是的话 查询设计部门的人
        DesignRole designRole = designRoleService.queryRoleByCode(code);

        LambdaQueryWrapper<DesignDept> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DesignDept::getDelFlag, Constants.DEL_FLAG_NO);

        if (designRole != null && designRole.getRoleKey().contains("admin")) {
            queryWrapper.eq(DesignDept::getDeptFunctions, "2");
        }else {
            queryWrapper.eq(DesignDept::getLeader, code);
        }
        //判断是否是部门负责人

        List<DesignDept> addList = new ArrayList<>();
        List<DesignDept> directDepts = designDeptMapper.selectList(queryWrapper);
        addList.addAll(directDepts);
        if (!CollectionUtils.isEmpty(directDepts)) {
            List<Long> list = directDepts.stream().map(DesignDept::getDeptId).collect(Collectors.toList());
            for (Long l : list) {
                List<DesignDept> designDepts = designDeptMapper.selectByAncestorId(l);
                addList.addAll(designDepts);
            }
            List<Long> listQuery = addList.stream().map(DesignDept::getDeptId).collect(Collectors.toList());
            return userMapper.selectList(Wrappers.lambdaQuery(CustomUser.class).in(CustomUser::getDeptId, listQuery).eq(CustomUser::getDelFlag, Constants.DEL_FLAG_NO));
        }
        return null;
    }
    public List<CustomUser> queryUserBydeptId(Long deptId) {
        List<DesignDept> deptList = deptService.queryAllDept(deptId);
        List<Long> longs = deptList.stream().map(DesignDept::getDeptId).collect(Collectors.toList());
        LambdaQueryWrapper<CustomUser> wrapper = Wrappers.lambdaQuery();
        wrapper.in(CustomUser::getDeptId, longs).eq(CustomUser::getDelFlag, Constants.DEL_FLAG_NO);
        return userMapper.selectList(wrapper);
    }
}
